package com.alex.server.config;

import com.alex.server.mapper.MailLogMapper;
import com.alex.server.pojo.MailConstants;
import com.alex.server.pojo.MailLog;
import com.alex.server.service.IMailLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



/**
 * rabbitmq配置类
 */
@Configuration
public class RabbitMqConfig {
    //打印日志
    private static final Logger logger= LoggerFactory.getLogger(RabbitMqConfig.class);
    @Autowired
    public CachingConnectionFactory cachingConnectionFactory;
    @Autowired
    public IMailLogService mailLogService;
    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        /**
         * 消息确认回调,确认消息是否到达broker
         * data:消息唯一标识
         * ack:确认结果
         * cause:失败原因
         */
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) ->{
            //如果消息发送成功,则确认结果为1,把消息打印出来,并且修改数据库中信息的状态
            String msgId = correlationData.getId();
            if (ack){
               logger.info("消息发送成功",msgId);
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",1).eq("msgId",msgId));
           }else {
                logger.info("消息发送失败",msgId);
            }
            /**
             * 消息发送失败回调
             * 比如router不到queue
             * message:消息主题
             * repCode:响应码
             * repText:相应描述
             *
             */
            rabbitTemplate.setReturnCallback((message, repCode,repText,exchange,routingKey) ->{
                logger.info("消息发送失败",msgId);
            } );
        } );
        return rabbitTemplate;
    }
    @Bean
    public Queue queue(){
        return new Queue(MailConstants.Queue_name);
    }
    @Bean
    public TopicExchange exchange(){
        return  new TopicExchange(MailConstants.EXCHANGE_name);
    }
    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(exchange()).with(MailConstants.ROUTING_KEY);
    }
}
